//
//  YZXUserAccountVM.swift
//  YZXWeibo
//
//  Created by 叶周翔 on 16/7/21.
//  Copyright © 2016年 叶周翔. All rights reserved.
//

/*
这个类负责YZXUserAccount的业务逻辑
网络请求
字典转模型
解档和归档
*/


import UIKit

class YZXUserAccountVM: NSObject {
    /**
     单例
     */
    static let shareUserAccountVM: YZXUserAccountVM = YZXUserAccountVM()
    
    //判断用户是否登录
    var userLogin: Bool{
        get{
            // 用户的账号不为空 表示有账号登录
            return userAccount != nil
        }
    }
    
    // 以后访问账号只需要访问这个属性？？？？
    var userAccount: YZXUserAccount?
    
    override init() {
        super.init()
        userAccount = loadAccount()
        
        
    }
    
    // 账号保存的路径
    let userAccountFile = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingString("/userAccount.plist")
    
    
    
    // 读取用户的信息
    func loadUserInfo(completion:(error:NSError?) -> ()){
        // 判断是否有access_token
        guard let access_token = userAccount?.access_token else{
            return
            
        }
        // 没有uid也不能往下执行
        guard let uid = userAccount?.uid else{
            return
        }
        
        let urlString = "2/users/show.json"
        let paraments = [
            "access_token":access_token,
            "uid":uid
        ]
        
        YZXNetworkTool.shareNetworkTool.GET(urlString, parameters: paraments, progress: nil, success: { (_, respondObject) -> Void in
            let dict = respondObject as! [String:AnyObject]
            // 获取用户的头像和用户名
            let screen_name = dict["screen_name"] as? String
            let avatar_large = dict["avatar_large"] as? String
            
            self.userAccount?.screen_name = screen_name
            self.userAccount?.avatar_large = avatar_large
            // 保存到沙盒中
            NSKeyedArchiver.archiveRootObject(self.userAccount!, toFile: self.userAccountFile)
            completion(error: nil)
            
            }) { (_, error) -> Void in
                completion(error: error)
        }
        
    }
    
    
     func loadAccess_Token(code:String) -> Void{
        let urlString = "https://api.weibo.com/oauth2/access_token"
        // 请求参数
        let paraments = [
            "client_id": client_id,
            "client_secret": client_secret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirect_uri
        ]
        
        // 使用afn发送POST请求
        YZXNetworkTool.shareNetworkTool.POST(urlString, parameters: paraments, progress: nil, success: { (_, resopnseOjbect) -> Void in
            
//            print("\(resopnseOjbect)")
            // 字典转模型
            let dict = resopnseOjbect as! [String:AnyObject]
            
            self.userAccount = YZXUserAccount(dic: dict)
            // 保存到沙盒中
            NSKeyedArchiver.archiveRootObject(self.userAccount!, toFile: self.userAccountFile)
            
            }) { (_, error) -> Void in
                
                print("\(error)")
        }
        
    }
    /**
    *  读取账号 也有可能是读取不到账号的 比如第一次登陆的时候
    */
    func loadAccount() -> YZXUserAccount?{
        // 从沙盒中读取账号
        let account = NSKeyedUnarchiver.unarchiveObjectWithFile(userAccountFile) as? YZXUserAccount
        if account != nil && account?.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending{
//            print("没有过期的账号")
            return account
        }
        return nil
    }
}